const axios = require('axios');
const fs = require('fs');
const XLSX = require('xlsx');

const url = 'http://localhost:9527/api-cemc/items/pagedstat?hostid=1001554&groupid=-1&name=&applicationName=&key=&delay=&history=&trends=&type=-1&valueType=-1&state=-1&status=-1&hadTrigger=-1&hadTemplate=-1&subApplicationNames=&subTypes=&subValueTypes=&subStates=&subHadTemplates=&subHadTriggers=&subHasDiscoveries=&subHistories=&subTrends=&subDelays=&sort=name%2Casc&page=0&size=2000&checkValue=false&action=&totalCount=0';

// 请求头配置
const headers = {
  'Accept': 'application/json, text/plain, */*',
  'Accept-Language': 'zh-CN,zh;q=0.9',
  'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJyb290Iiwic2Vzc2lvbmlkIjoiNjkwNGM0ZjUxNjZjNTUwNDBjN2U1NzYwNDNhZTU0NjkiLCJleHAiOjE3MzM5OTMwMTQsImlhdCI6MTczMzk4OTQxNH0.9Y2RvMPJQFOUS92s3ri1NgTU4y83CziBmhf5-_81rhBvKwcPJs-Uj5sjF5Way6Wqbe02p5OpiekS3afwWPzEPw',
  'Connection': 'keep-alive',
  'Cookie': 'authorized-token={%22accessToken%22:%22eyJhbGciOiJIUzUxMiJ9.admin%22%2C%22expires%22:1919520000000%2C%22refreshToken%22:%22eyJhbGciOiJIUzUxMiJ9.adminRefresh%22}; multiple-tabs=true; sidebarStatus=0',
  'Referer': 'http://localhost:9527/cemc/maintainmonitoring/itemlist?filterSet=1&hostid=1004776',
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
  'dnt': '1'
};

axios.get(url, { headers })
  .then(({data}) => {
    // 检查返回数据的结构是否符合预期
    if (data.result && Array.isArray(data.result.itemData.content)) {
      const jsonData = data.result.itemData.content;
      const itemArray = [];


      // 按 appName 分类数据
      const categorizedData = {};

      jsonData.forEach(item => {
        let appname = '其他';
          if (item.belongApplicationList && item.belongApplicationList[0]) {
            appname = item.belongApplicationList[0].name;
          }
        if (!categorizedData[appname]) {
          categorizedData[appname] = []; // 如果该类别不存在，先初始化为空数组
        }
        categorizedData[appname].push({
          name: item.name,
          appName: appname
        });
      });

      if (categorizedData) {
        fs.writeFile('D:/item.json', JSON.stringify(categorizedData, null, 2), (err) => {
          if (err) {
            console.error('写入文件失败:', err);
          } else {
            console.log('数据已成功写入item.json文件');
          }
        });
      }
    } else {
      console.error('返回的数据结构不符合预期，无法处理内容');
      console.log(data); // 输出返回的数据以便调试
    }
  })
  .catch(error => {
    console.error('请求失败:', error);
  });
